<?php
/**
 * MongodbManager.php
 *
 * @author camfee <camfee@foxmail.com>
 * @date   17-9-28 上午11:28
 *
 */

namespace Center;

use Common\MongoDbBase;

class MongodbManager
{
    private static $_mongo = null;

    private static function getMongo($db = 'test', $collection = 'test')
    {
        if (empty(self::$_mongo)) {
            self::$_mongo = new MongoDbBase($db, $collection);
        }

        return self::$_mongo;
    }

    /**
     * 获取数据库列表
     *
     * @return array
     */
    public static function getDataBases()
    {
        $dbs = [];
        foreach (self::getMongo()->getDataBases() as $db) {
            $db = (array)$db;
            $name = current($db)['name'];
            $dbs[$name] = $name;
        }

        return $dbs;
    }

    /**
     * 新建集合
     *
     * @param string $db         数据库
     * @param string $collection 集合名称
     * @return array|object
     */
    public static function createCollection($db, $collection)
    {
        return self::getMongo()->createCollection($db, $collection);
    }

    /**
     * 删除集合
     *
     * @param string $db         数据库
     * @param string $collection 集合名称
     * @return bool
     */
    public static function deleteCollection($db, $collection)
    {
        $ret = self::getMongo()->deleteCollection($db, $collection);
        $ret = (array)$ret;
        if (!empty($ret['ok'])) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取数据库集合列表
     *
     * @param string $db 数据库
     * @param array  $options
     * @return array
     */
    public static function getCollections($db, $options = [])
    {
        $collects = [];
        foreach (self::getMongo()->getCollections($db, $options) as $collection) {
            $collection = (array)$collection;
            $name = current($collection)['name'];
            if (stripos($name, 'system.') !== 0) {
                $collects[$name] = $name;
            }
        }

        return $collects;
    }
}